<template>
  <div>
    <el-select
      v-model="data.selectVal"
      placeholder="请选择"
      style="width: 100%"
      clearable
      @change="select"
    >
      <el-option
        v-for="item in data.initOption"
        :key="item.id"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-select>
  </div>
</template>

<script>
import { reactive, onMounted } from "@vue/composition-api";

export default {
  name: "index",
  props: {
    config: {
      type: Object,
      default: () => {
      }
    },
    selectData: {
      type: Object,
      default: () => {
      }
    }
  },
  setup(props, { emit }) {
    /**
     * data
     */
    const data = reactive({
      selectVal: "",
      initOption: [],
      option: [
        { label: "姓名", value: "truename" },
        { label: "手机号", value: "phone" },
        { label: "邮箱", value: "email" },
        { label: "ID", value: "id" },
        { label: "标题", value: "title" }
      ]
    });
    /**
     * methods 方法
     */
      // 初始化
    const initOption = () => {
        let initData = props.config.init;
        // 数据校验
        if (initData.length === 0) {
          console.log("config的参数是空，无法显示下拉菜单");
          return false;
        }
        let optionArr = [];
        initData.forEach(item => {
          let arr = data.option.filter(ele => ele.value === item); // filter匹配成功后返回一个数组，需要取下标第一个
          if (arr.length > 0) {
            optionArr.push(arr[0]);
          }
        });
        // 数据校验
        if (optionArr.length === 0) {
          console.log("匹配的数据为空");
          return false;
        }
        // 初始化赋值
        data.initOption = optionArr;
        // 初始化搜索类型
        data.selectVal = optionArr[0].value;
        // 返回初始值
        emit("update:selectData", optionArr[0]);
      };

    // 选择触发
    const select = (val) => {
      let filterData = data.option.filter(item => item.value === val)[0];
      emit("update:selectData", filterData);
    };
    /**
     * watch 监听
     */

    /**
     * 生命周期
     */
    onMounted(() => {
      initOption();
    });
    return {
      data,
      select
    };
  }
};
</script>

<style scoped></style>
<!--
组件目录位置：src > components > select > index.vue
组件引用方式：import selectVue from "@c/select";
template  <selectVue :config="data.configOption"/>

参数配置：
configOption: {
    init: [],
},
init:
    数据类型: Array,
    可配置的数据："name", "phone", "email", "id", "title"
...
-->

